#!/bin/sh

#升级时要保留的数据库
database_path='/userdata/dgri/app/DataCenter/bin/egw_db-20210707.db'
#数据库暂存路径
backup_path='/userdata/dgri/data/DataCenter'
backup_database_path='/userdata/dgri/data/DataCenter/egw_db-20210707.db'
#zlog日志配置路径
zlog_cfg_path='/userdata/dgri/zlog.d/'

# 1 备份数据库
if [ -f $database_path ];then
    if [ ! -d "$backup_path" ]; then
        mkdir -p "$backup_path"
    fi
    mv $database_path $backup_path
    echo "$database_path exist"
else
    echo "$database_path not exist"
fi

# 定义全局app名称
app_name="DataCenter"

# 2 获取app_name的运行状态
app_status=$(appm -l | grep $app_name | awk '{print $2}')
if [ "$app_status" == "RUNNING" ]; then
    echo "$app_name is running, stopping it..."
    appm -S -n $app_name
    if [ $? -ne 0 ]; then
        echo "Failed to stop $app_name"
        exit 1
    fi
    app_was_running=true
    sleep 2
else
    echo "$app_name is not running"
    app_was_running=false
fi

# 3 升级数据中心程序
cp -r ./bin ../
if [ $? -ne 0 ];then
    exit 1
fi
cp -r ./lib ../
if [ $? -ne 0 ];then
    exit 1
fi

# 4 恢复数据库文件
if [ -f $backup_database_path ];then
    mv $backup_database_path $database_path
    echo "$backup_database_path exist"
    # rm $backup_database_path
else
    echo "$backup_database_path not exist"
fi

# 5 备份ProductSection.json
cp -r ./ProductSection.json ../
if [ $? -ne 0 ];then
    exit 1
fi

#拷贝zlog配置文件
if [ ! -d $zlog_cfg_path ];then
    echo "$zlog_cfg_path not exist, mkdir"
    mkdir $zlog_cfg_path
fi

cp ./DataCenter.zconf $zlog_cfg_path
if [ $? -ne 0 ];then
    echo "cp DataCenter.zconf to $zlog_cfg_path fail"
    exit 1
fi

# 6 如果之前app_name是运行状态，重新启动它
if [ "$app_was_running" == true ]; then
    echo "Restarting $app_name..."
    appm -s -n $app_name
    if [ $? -ne 0 ]; then
        echo "Failed to restart $app_name"
        exit 1
    fi
    echo "$app_name restarted successfully"
fi

exit 0
